package com.aso114.project.exam;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.MsgEvent;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.bean.QuestionContextListBean;
import com.aso114.project.bean.questioncontentListBean;
import com.aso114.project.commonview.NoPreloadViewPager;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.MySharedPreferences;
import com.aso114.project.util.SystemBarHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by asus on 2019/1/15.
 * 申论练习
 */

public class ExpositionTestActivity extends BaseSimpleActivity {
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.layout_title_bar_right_iv)
    ImageView layoutTitleBarRightIv;
    @BindView(R.id.layout_title_bar_right_tv)
    TextView layoutTitleBarRightTv;
    @BindView(R.id.expostion_conect)
    TextView expostionConect;
    @BindView(R.id.expostion_num)
    TextView expostionNum;
    @BindView(R.id.expostion_viewpager)
    NoPreloadViewPager expostionViewpager;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.collect)
    TextView collect;
    @BindView(R.id.submit)
    TextView submit;
    @BindView(R.id.stop)
    TextView stop;
    @BindView(R.id.setting)
    TextView setting;
    @BindView(R.id.main_bar)
    LinearLayout mainBar;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;

    TextView first, second, three, four, five;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;

    private int pagerPosition = 0;
    private ArrayList<QuestionBaseBean> baseBean;
    private ArrayList<QuestionContextListBean> baseListBean;
    private int EXPOSITION_STAR_TYPE = 7;
    private int position = 0;

    private boolean isCollect;

    @Override
    protected int getResouseId() {
        return R.layout.activity_expostion_test;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        layoutTitleBarTitleTv.setText("真题模考");
        position = getIntent().getIntExtra("position", 0);
        isCollect = getIntent().getBooleanExtra("isCollect", false);
        expostionViewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        expostionViewpager.setOnPageChangeListener(new MyPagerChangeListner());
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(QuestionBean event) {
        Log.i("yxp", "------------------1");

        baseBean = new ArrayList<>();
        baseListBean = event.getQuestionsContextList();
        for (int i = 0; i < event.getQuestionBaseList().size(); i++) {
            for (int j = 0; j < event.getQuestionBaseList().get(i).getQuestionList().size(); j++) {
                QuestionBaseBean questionBaseBean = new QuestionBaseBean();

                questionBaseBean.setQuestionBaseId(event.getQuestionBaseList().get(i).getQuestionBasicId());
                questionBaseBean.setPaperId(event.getQuestionBaseList().get(i).getPaperId());
                questionBaseBean.setQuantity(event.getQuestionBaseList().get(i).getQuantity());
                questionBaseBean.setTitle(event.getQuestionBaseList().get(i).getTitle());
                questionBaseBean.setDescription(event.getQuestionBaseList().get(i).getDescription());
                questionBaseBean.setRealPaperId(event.getQuestionBaseList().get(i).getRealPaperId());
                questionBaseBean.setRealBaseId(event.getQuestionBaseList().get(i).getRealBaseId());
                questionBaseBean.setQuestionId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionId());
                questionBaseBean.setCateId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getCateId());
                questionBaseBean.setBaseId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getBaseId());
                questionBaseBean.setUserId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserId());
                questionBaseBean.setRealQuestionId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getRealQuestionId());
                questionBaseBean.setOrderNumber(event.getQuestionBaseList().get(i).getQuestionList().get(j).getOrderNumber());
                questionBaseBean.setRealPaperTitle(event.getQuestionBaseList().get(i).getQuestionList().get(j).getRealPaperTitle());
                questionBaseBean.setFormatContent(event.getQuestionBaseList().get(i).getQuestionList().get(j).getFormatContent());
                questionBaseBean.setFormatImages(event.getQuestionBaseList().get(i).getQuestionList().get(j).getFormatImages());
                questionBaseBean.setExamPaperType(event.getQuestionBaseList().get(i).getQuestionList().get(j).getExamPaperType());
                questionBaseBean.setQuestionScore(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionScore());
                questionBaseBean.setErrorScore(event.getQuestionBaseList().get(i).getQuestionList().get(j).getErrorScore());
                questionBaseBean.setErrorScoreType(event.getQuestionBaseList().get(i).getQuestionList().get(j).getErrorScoreType());
                questionBaseBean.setDeductionScore(event.getQuestionBaseList().get(i).getQuestionList().get(j).getDeductionScore());
                questionBaseBean.setDifficultyFactor(event.getQuestionBaseList().get(i).getQuestionList().get(j).getDifficultyFactor());
                questionBaseBean.setContextQuestionId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getContextQuestionId());
                questionBaseBean.setAnswerCount(event.getQuestionBaseList().get(i).getQuestionList().get(j).getAnswerCount());
                questionBaseBean.setAnswerErrorCount(event.getQuestionBaseList().get(i).getQuestionList().get(j).getAnswerErrorCount());
                questionBaseBean.setQuestionTypeId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionTypeId());
                questionBaseBean.setSpecialId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getSpecialId());
                questionBaseBean.setCollect("1".equals(event.getQuestionBaseList().get(i).getQuestionList().get(j).getIsCollect()));

                QuestionBaseBean.questionStatisticsInfo questionStatisticsInfo = new QuestionBaseBean.questionStatisticsInfo();
                questionStatisticsInfo.setQuestionStatisticId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionStatisticsInfo().getQuestionStatisticId());
                questionStatisticsInfo.setQuestionId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionStatisticsInfo().getQuestionId());
                questionStatisticsInfo.setRightRatio(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionStatisticsInfo().getRightRatio());
                questionStatisticsInfo.setRightCount(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionStatisticsInfo().getRightCount());
                questionStatisticsInfo.setWrongRatio(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionStatisticsInfo().getWrongRatio());
                questionStatisticsInfo.setWrongCount(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionStatisticsInfo().getWrongCount());
                questionBaseBean.setQuestionStatisticsInfo(questionStatisticsInfo);

                QuestionBaseBean.QuestionsAnswerInfo questionsAnswerInfo = new QuestionBaseBean.QuestionsAnswerInfo();
                questionsAnswerInfo.setQuestionId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getQuestionId());
                questionsAnswerInfo.setAnswerArray(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getAnswerArray());
                questionsAnswerInfo.setFormatContent(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getFormatContent());
                questionsAnswerInfo.setFormatImages(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getFormatImages());
                questionBaseBean.setQuestionsAnswerInfo(questionsAnswerInfo);

                QuestionBaseBean.userAnswerInfo userAnswerInfo = new QuestionBaseBean.userAnswerInfo();

                userAnswerInfo.setAnswerDuration(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getAnswerDuration());
                userAnswerInfo.setIsState(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getIsState());

                userAnswerInfo.setPaperId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getPaperId());
                userAnswerInfo.setRealQuestionId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getRealQuestionId());
                userAnswerInfo.setQuestionNumber(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getQuestionNumber());
                userAnswerInfo.setQuestionScore(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getQuestionScore());
                userAnswerInfo.setCateId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getCateId());
                userAnswerInfo.setUserAnswer(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getUserAnswer());
                userAnswerInfo.setUserAnswerId(event.getQuestionBaseList().get(i).getQuestionList().get(j).getUserAnswerInfo().getUserAnswerId());

                questionBaseBean.setUserAnswerInfo(userAnswerInfo);

                ArrayList<questioncontentListBean> questioncontentListBeans = new ArrayList<>();
                questioncontentListBeans.addAll(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestioncontentList());
                questionBaseBean.setQuestioncontentList(questioncontentListBeans);

                baseBean.add(questionBaseBean);
                expostionConect.setText(baseBean.get(expostionViewpager.getCurrentItem()).getTitle());
                expostionNum.setText((expostionViewpager.getCurrentItem() + 1) + "/" + baseBean.size());
                expostionViewpager.setCurrentItem(position, false);
            }
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.layout_title_bar_back_iv, R.id.collect, R.id.submit, R.id.setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;
            case R.id.collect:
                if (baseBean.get(pagerPosition).isCollect() == false) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                            .getMinimumHeight());

                    collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                    collect.setTextColor(getResources().getColor(R.color.aff6559));
                    baseBean.get(pagerPosition).setCollect(true);
                    setCollect();
                } else {
                    Drawable drawable = getResources().getDrawable(R.mipmap.erji_sc_ic);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                            .getMinimumHeight());

                    collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                    collect.setTextColor(getResources().getColor(R.color.a999999));
                    baseBean.get(pagerPosition).setCollect(false);
                    delCollect();
                }
                break;
            case R.id.submit:
                EventBus.getDefault().postSticky(baseBean);
                Intent intent = new Intent(this, ExpositionCardActivity.class);
                startActivityForResult(intent, EXPOSITION_STAR_TYPE);
                break;
            case R.id.setting:
                showProductDialog();
                break;
        }
    }

    private void delCollect() {
        CommentModel.getInstant().delCollect(Constant.essay, baseBean.get(pagerPosition).getRealQuestionId(), new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                Helper.showToast("取消收藏");
            }

            @Override
            public void onFailure(String fail) {

            }
        });
    }

    private void setCollect() {
        CommentModel.getInstant().setCollect(Constant.essay, baseBean.get(pagerPosition).getRealQuestionId(), new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                Helper.showToast("已收藏");
            }

            @Override
            public void onFailure(String fail) {

            }
        });
    }

    //设置字体大小
    private void showProductDialog() {

        View view = LayoutInflater.from(this).inflate(R.layout
                .questionseting, null);

        first = (TextView) view.findViewById(R.id.first);
        second = (TextView) view.findViewById(R.id.second);
        three = (TextView) view.findViewById(R.id.three);
        four = (TextView) view.findViewById(R.id.four);
        five = (TextView) view.findViewById(R.id.five);

        int size = MySharedPreferences.getInstance(this).getTextSize();
        switch (size) {
            case 1:
                textSelect(first);
                break;
            case 2:
                textSelect(second);
                break;
            case 3:
                textSelect(three);
                break;
            case 4:
                textSelect(four);
                break;
            case 5:
                textSelect(five);
                break;
        }
        // 创建PopupWindow对象，指定宽度和高度
        PopupWindow window = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT);

        // 设置可以获取焦点
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        // 设置可以触摸弹出框以外的区域
        window.setOutsideTouchable(true);
        // 更新popupwindow的状态
        window.update();
        // 以下拉的方式显示，并且可以设置显示的位置
//        window.showAsDropDown(tvProduct, 0, 20);
//        window.showAtLocation(setting, Gravity.CENTER | Gravity.BOTTOM, 0, 160);
        int[] location = new int[2];
        mainBar.getLocationOnScreen(location);
        //在控件上方显示
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = view.getMeasuredWidth();
        int popupHeight = view.getMeasuredHeight();
        window.showAtLocation(mainBar, Gravity.NO_GRAVITY, (location[0] + mainBar.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight);

        view.findViewById(R.id.first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(expostionViewpager.getCurrentItem(), 1));
                MySharedPreferences.getInstance(ExpositionTestActivity.this).setTextSize(1);
                textSelect(first);
            }
        });

        view.findViewById(R.id.second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(expostionViewpager.getCurrentItem(), 2));
                MySharedPreferences.getInstance(ExpositionTestActivity.this).setTextSize(2);
                textSelect(second);
            }
        });


        view.findViewById(R.id.three).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(expostionViewpager.getCurrentItem(), 3));
                MySharedPreferences.getInstance(ExpositionTestActivity.this).setTextSize(3);
                textSelect(three);
            }
        });

        view.findViewById(R.id.four).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(expostionViewpager.getCurrentItem(), 4));
                MySharedPreferences.getInstance(ExpositionTestActivity.this).setTextSize(4);
                textSelect(four);
            }
        });

        view.findViewById(R.id.five).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(expostionViewpager.getCurrentItem(), 5));
                MySharedPreferences.getInstance(ExpositionTestActivity.this).setTextSize(5);
                textSelect(five);
            }
        });

    }

    private void textSelect(TextView view) {
        first.setSelected(false);
        second.setSelected(false);
        three.setSelected(false);
        four.setSelected(false);
        five.setSelected(false);
        view.setSelected(true);
    }

    class MyPagerChangeListner implements NoPreloadViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            expostionConect.setText(baseBean.get(position).getTitle());
            expostionNum.setText((position + 1) + "/" + baseBean.size());
        }

        @Override
        public void onPageSelected(int position) {
            pagerPosition = position;
            expostionConect.setText(baseBean.get(position).getTitle());
            expostionNum.setText((position + 1) + "/" + baseBean.size());

            if (baseBean.get(position).isCollect() == true) {
                Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                        .getMinimumHeight());

                collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                collect.setTextColor(getResources().getColor(R.color.aff6559));
            } else {
                Drawable drawable = getResources().getDrawable(R.mipmap.erji_sc_ic);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                        .getMinimumHeight());

                collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                collect.setTextColor(getResources().getColor(R.color.a999999));
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return ExpositionFragment.newInstance(position, baseBean.get(position), baseListBean,isCollect);
        }

        @Override
        public int getCount() {
            if (baseBean == null || baseBean.size() == 0) {
                return 0;
            } else {
                return baseBean.size();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == EXPOSITION_STAR_TYPE) {
                int position = data.getIntExtra("position", 0);
                expostionViewpager.setCurrentItem(position, false);
            }
        }
    }
}
